# -*- coding: UTF-8 -*-
"""
@Time:2022/4/30 10:35
@File:home.py
@Author:常雷
@Software:PyCharm
"""
import datetime
from rest_framework.response import Response
from django.shortcuts import render, HttpResponse
from rest_framework import serializers
from rest_framework.views import APIView
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView
from palyWordDackend import models
from django.forms import model_to_dict
from rest_framework import status
from django.db.models import F
import uuid
import requests


class ArticleModelSerializers(serializers.ModelSerializer):
    """序列化"""
    # 重写字段信息
    user = serializers.SerializerMethodField()
    topic = serializers.SerializerMethodField()

    class Meta:
        model = models.Article
        fields = "__all__"


class ArticleView(APIView):
    def get(self, request, *args, **kwargs):
        queryset = models.Article.objects.all().order_by('-id')[0:10]
        ser = ArticleModelSerializers(instance=queryset, many=True)
        return Response(ser.data, status=200)


class CategoryModelSerializers(serializers.ModelSerializer):
    """序列化"""

    class Meta:
        model = models.Category
        fields = "__all__"


class CategoryView(APIView):
    def get(self, request, *args, **kwargs):
        queryset = models.Category.objects.all().order_by('-hot_count')[0:4]
        ser = CategoryModelSerializers(instance=queryset, many=True)
        # print(ser.data)
        return Response(ser.data, status=200)


class ActiveUserViewModelSerializers(serializers.ModelSerializer):
    """序列化"""
    creat_time = serializers.SerializerMethodField()

    class Meta:
        model = models.UserInfo
        fields = ['username', 'is_active', 'creat_time', 'phone']

    def get_creat_time(self, obj):
        return obj.creat_time.strftime("%Y年%m月")


class ActiveUserView(APIView):
    def get(self, request, *args, **kwargs):
        queryset = models.UserInfo.objects.all().order_by('-is_active')[0:4]
        ser = ActiveUserViewModelSerializers(instance=queryset, many=True)
        # print(ser.data)
        return Response(ser.data, status=200)


# 显示文章
"""分页器"""
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.filters import BaseFilterBackend


class OldBoyLimitOffsetPagination(LimitOffsetPagination):
    """此处分页器帮助我们切片处理"""
    default_limit = 5
    max_limit = 50
    limit_query_param = 'limit'  # get后跟数据,数据条数
    offset_query_param = 'offset'  # get后跟数据,数据开始位置

    def get_offset(self, request):
        return 0

    def get_paginated_response(self, data):
        """get后添加一些数据"""
        return Response(data)


class MinFilterBackend(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        min_id = request.query_params.get('min_id')
        if min_id:
            return queryset.filter(id__lt=min_id).order_by('-id')
        return queryset


class MaxFilterBackend(BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        max_id = request.query_params.get('max_id')
        if max_id:
            return queryset.filter(id__gt=max_id).order_by('id')
        return queryset


class HotArticleViewSerializers(serializers.ModelSerializer):
    """序列化"""
    # 重写字段信息
    category = serializers.SerializerMethodField()
    tags = serializers.SerializerMethodField()
    user = serializers.SerializerMethodField()

    # create_time = serializers.SerializerMethodField()
    class Meta:
        model = models.Article
        # fields = ['title', 'desc','id','create_time', 'hot_count','cover', 'content', 'user', 'favor_count']
        # fields = "__all__"
        exclude = ['content']

    # 取值方法2
    def get_user(self, obj):
        # model_to_dict fields:需要字段列表,exclude:不需要字段
        return model_to_dict(obj.user, fields=['id', 'username', 'avatar'])

    def get_tags(self, obj):
        detail_queryset = models.Tag.objects.filter(article=obj)
        return [model_to_dict(row, ['id', 'name']) for row in detail_queryset]

    def get_category(self, obj):
        return model_to_dict(obj.category, fields=['id', 'name'])


class HotArticleView(APIView):
    def get(self, request, *args, **kwargs):
        # print(request.data)
        query_type = request.query_params.get('query_type')
        print(query_type)
        queryset = models.Article.objects.all().order_by(query_type)[0:10]
        # queryset = models.Article.objects.filter(user_id=user_id).order_by('-hot_count')[0:10]
        ser = HotArticleViewSerializers(instance=queryset, many=True)
        # print(type(ser.data[0]))
        return Response(ser.data, status=200)
